#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>

#include "libradarssd.h"
#define SYNC_COUNT 2048

unsigned long elapsed(struct timeval* begin, struct timeval* end){
    long seconds = end->tv_sec - begin->tv_sec;
    long microseconds = end->tv_usec - begin->tv_usec;
    return seconds*1e6 + microseconds;
}

int main(){
    struct timeval begin, end;
    gettimeofday(&begin, 0);

    u64 test_time = 8*44738560;
    //u64 test_time = 32*1000*1000; //generate for ai test
    u64 write_signal = 0;
    int pagesize = getpagesize();
    int buffer_size = ((sizeof(ftype)*SYNC_COUNT*FEATURE_COUNT+pagesize-1)/pagesize)*pagesize;
    ftype* buffer = NULL;
    posix_memalign((void*)&buffer, getpagesize(), buffer_size);
    //for bufferd io
    //ftype buffer[SYNC_COUNT*FEATURE_COUNT] = {0};

    unsigned index=0;
    for(int i=0;i<test_time;i++){
        buffer[index] = i;
        buffer[index+1] = i+1;
        buffer[index+2] = i+2;
        index += 3;
        write_signal += 1;

        if(i%SYNC_COUNT==0){
            index = 0;
            //write to file
            char filepath[60] = {0};
            sprintf(filepath, "/mnt/f2fs/%d",i/SYNC_COUNT);
            //sprintf(filepath, "/home/gary/Code/dataset/radar_fs_test/%d",i/SYNC_COUNT);
            int fd = open(filepath, O_CREAT | O_RDWR | O_DIRECT);
            if(fd < 0){
                printf("Open Error:%d\n",fd);
                return 0;
            }
            int write_result = write(fd, buffer, sizeof(ftype)*SYNC_COUNT*FEATURE_COUNT);
            if(write_result<0){
                printf("Error code:%d\n",write_result);
            }
            close(fd);
            free(buffer);
            posix_memalign((void*)&buffer, getpagesize(), buffer_size);
            //Too Fast!!!!!!!!!
            // FILE* fp;
            // fp = fopen(filepath, "a");
            // fwrite(buffer, sizeof(ftype), SYNC_COUNT*FEATURE_COUNT, fp);
            // fclose(fp);
        }
    }
    free(buffer);
    gettimeofday(&end, 0);

    printf("total elapsed %lu us(%f s)\n",elapsed(&begin, &end),elapsed(&begin, &end)/1000000.0);

    float MB = write_signal*FEATURE_SIZE*FEATURE_COUNT / (float)(1024*1024);
    float bandwith = MB/((double)elapsed(&begin, &end)/1000000);
    double average_latency = (double)elapsed(&begin, &end)/write_signal;
    printf("write %lu signals in %.2f MB\nBandwith:%.2f MB/s\nAverage latency:%.4lf us/signal\n",write_signal,MB,bandwith,average_latency);

    return 0;
}
